//
//  MyViewController.m
//  Article
//
//  Created by LONG on 16/4/21.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MyViewController.h"
#import "EditorTableViewCell.h"
#import "EditViewController.h"
#import "Model.h"
@interface MyViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)NSMutableArray *dataarr;

@end

@implementation MyViewController{
    UITableView *_myTableView;
    __block int page;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self requestTableview];
    [self myTableView];
}
- (UITableView *)myTableView{
    if (nil == _myTableView){
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-143)];
        _myTableView.backgroundColor = [UIColor whiteColor];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        [_myTableView registerNib:[UINib nibWithNibName:@"EditorTableViewCell" bundle:nil] forCellReuseIdentifier:@"EditorTableViewCell"];
        
        [_myTableView addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(downMJ)];
        
        [self setExtraCellLineHidden:_myTableView];
        
        UILongPressGestureRecognizer *longPressReger = [[UILongPressGestureRecognizer alloc]
                                                        
                                                        initWithTarget:self action:@selector(handleLongPress:)];
        
        longPressReger.minimumPressDuration = 0.5;
        
        [_myTableView addGestureRecognizer:longPressReger];
        
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer

{
    
    CGPoint point = [gestureRecognizer locationInView:_myTableView];
    
    
    
    if(gestureRecognizer.state == UIGestureRecognizerStateBegan)
        
    {
         NSIndexPath *indexPath = [_myTableView indexPathForRowAtPoint:point];
        
    
        UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"是否删除" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * aa = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [ac dismissViewControllerAnimated:YES completion:nil];
            
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            
            Model*model=self.dataarr[indexPath.row];

            NSDictionary *dic = @{@"user_token":[user objectForKey:@"token"],
                                  @"id":model.id};
            NSLog(@">>>%@",dic);
            AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            
            [manager POST:ARTICLE_DEL_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                
                [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
                
                [self requestTableview];
            } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
                [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                
                if ([MyTools connectedToNetwork] == 0) {
                    [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
                }else{
                    [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
                }
            }];
            
        }];
        UIAlertAction *other = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [ac addAction:other];
        [ac addAction:aa];
        [self presentViewController:ac animated:YES completion:nil];

    

    }
    
    
}
//下拉刷新
-(void)downMJ{
    page = 1;
    [self requestTableview];
    [_myTableView.header endRefreshing];
}
//上拉加载
- (void)loadMoreData{
    page++;
    [self requestTableview];
    [_myTableView.footer endRefreshing];
    
}
- (void)requestTableview{
    if (_dataarr == nil || page == 1) {
        _dataarr = [NSMutableArray arrayWithCapacity:0];;
        
    }
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%d",page],
                          @"keywordtags":self.title};
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:ARTICLELIST_URL parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            //建立模型
            for (NSDictionary*dic in [responseObject objectForKey:@"data"]) {
                Model*model=[[Model alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                //追加数据
                [self.dataarr addObject:model];
            }
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
        if (_dataarr.count > 8) {
            [_myTableView addGifFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        }
        [_myTableView reloadData];
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}
#pragma mark tableView代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return _dataarr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EditorTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"EditorTableViewCell"];
    if (!cell) {
        cell=[[EditorTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"EditorTableViewCell"];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_dataarr.count == 0) {
        return cell;
    }
    Model*model=self.dataarr[indexPath.row];
    [cell configModel:model];
    cell.editBut.layer.masksToBounds = YES;
    cell.editBut.layer.cornerRadius = 6.0;
    cell.editBut.layer.borderWidth = 0.5;
    cell.editBut.layer.borderColor = [UIColorFromRGB(MYColor) CGColor];
    cell.editBut.tag = indexPath.row + 150;
    [cell.editBut addTarget:self action:@selector(editBut:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}
- (void)editBut:(UIButton *)but{
    Model*model=self.dataarr[but.tag - 150];
    
    EditViewController *evc = [[EditViewController alloc]init];
    evc.id = model.writing_id;
    evc.writing_img = model.writing_img;
    evc.writing_title = model.writing_title;
    [self.navigationController pushViewController:evc animated:YES];
}
#pragma mark delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 70;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Model*model=self.dataarr[indexPath.row];
    EditViewController *evc = [[EditViewController alloc]init];
    evc.id = model.writing_id;
    evc.writing_img = model.writing_img;
    evc.writing_title = model.writing_title;
    evc.writing_brief = model.writing_brief;
    [self.navigationController pushViewController:evc animated:YES];
}


-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
}
@end
